<template>
  <div class="ele-body ele-body-layout">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>Boss搜索账户报告</span>
      </div>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :highlight-current-row="true"
        :max-height="defaultHeight"
        :need-page="false"
        :parse-data="parseData"
        :selection.sync="selection"
        :summary-method="summaries"
        :where="where"
        show-summary
        @sort-change="sortChange"
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <!-- 搜索表单 -->
          <el-form
            :model="where"
            class="ele-form-search"
            label-width="75px"
            @keyup.enter.native="reload"
            @submit.native.prevent
          >
            <div class="app-container">
              <div class="filter-container">
                <el-select
                  v-model="where.bazaarId"
                  clearable
                  placeholder="推广市场"
                  style="width: 180px; margin-right: 6px"
                  @change="changebazaarId"
                >
                  <template v-for="item in bazaarList">
                    <el-option
                      v-if="item.status === 1"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </template>
                </el-select>

                <el-select
                  v-model="where.userid"
                  clearable
                  placeholder="推广账户"
                  style="width: 140px; margin-right: 6px"
                  @change="reload"
                >
                  <template v-for="item in expandList">
                    <el-option
                      v-if="item.status === 1"
                      :key="item.userid"
                      :label="item.username"
                      :value="item.userid"
                    />
                  </template>
                </el-select>

                <el-date-picker
                  v-model="daterange"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  end-placeholder="数据结束日期"
                  range-separator="-"
                  start-placeholder="数据开始日期"
                  style="width: 230px; margin-right: 6px"
                  type="datetimerange"
                  unlink-panels
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="onDateRangeChoose"
                />

                <el-button
                  icon="el-icon-search"
                  style="margin-right: 6px"
                  type="primary"
                  @click="reload"
                  >搜索
                </el-button>

                <el-button
                  icon="el-icon-refresh"
                  style="margin-left: 2px"
                  @click="reset"
                  >重置</el-button
                >
              </div>
            </div>
          </el-form>
        </template>

        <!-- 推广状态列 -->
        <template slot="userStat" slot-scope="{ row }">
          <div v-if="row.userStat === 1">
            <el-tag type="danger">开户金未到</el-tag>
          </div>
          <div v-if="row.userStat === 2"><el-tag>正常生效</el-tag></div>
          <div v-if="row.userStat === 3">
            <el-tag type="danger">余额为零</el-tag>
          </div>
          <div v-if="row.userStat === 4">
            <el-tag type="danger">未通过审核</el-tag>
          </div>
          <div v-if="row.userStat === 6">
            <el-tag type="danger">审核中</el-tag>
          </div>
          <div v-if="row.userStat === 7">
            <el-tag type="danger">被禁用</el-tag>
          </div>
          <div v-if="row.userStat === 8">
            <el-tag type="danger">待激活</el-tag>
          </div>
          <div v-if="row.userStat === 11">
            <el-tag type="danger">预算不足</el-tag>
          </div>
          <div v-if="row.userStat === 888" style="color: red">账户API错误</div>
          <div
            v-if="row.userStat !== 888 && row.countStat === 999"
            style="color: red"
          >
            统计API错误
          </div>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaarId" slot-scope="{ row }">
          <template v-for="item in bazaarList">
            <span v-if="row.bazaarId === item.id" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- 最后刷新时间列 -->
        <template slot="lastDatetime" slot-scope="{ row }">
          <span>
            <i class="el-icon-time"></i>
            {{ formatTime(row.lastDatetime) }}
          </span>
        </template>

        <!-- 账户昵称列 -->
        <template slot="username" slot-scope="{ row }">
          {{ asterisk(row.username, "*") }}
        </template>

        <!-- 账户预算列 -->
        <template slot="budget" slot-scope="{ row }">
          {{ row.budget ? row.budget : "不限定预算" }}
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{ row }">
          <el-link
            :underline="false"
            icon="el-icon-s-grid"
            type="primary"
            @click="openRegion(row)"
            >查看
          </el-link>
        </template>

        <!-- 现金消费列 -->
        <template slot="cash" slot-scope="{ row }">
          <el-popover
            placement="top-start"
            popper-class="cash-remove-popover"
            title="消费明细"
            trigger="hover"
            width="200"
            @hide="popoverHide"
          >
            现金消费{{ row.cash }}元, 账户返点: {{ row.rebate }}
            <span slot="reference" style="cursor: pointer">{{ row.cash }}</span>
          </el-popover>
        </template>

        <!-- 点击率列 -->
        <template slot="ctr" slot-scope="{ row }">
          <span>{{ row.ctr }}% </span>
        </template>

        <!-- OCPC成本列 -->
        <template slot="ocpccost" slot-scope="{ row }">
          <span>{{ getOcpccost(row.cost, row.ocpc) }} </span>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 地域弹窗 -->
    <vue-regiontarget
      :data="regionTarget"
      :visible.sync="showRegionTarget"
      @done="reload"
    />
  </div>
</template>

<script>
import baiduRegion from "@/assets/json/json.json";
import VueRegiontarget from "./vue-regiontarget";

export default {
  name: "semReport",
  components: { VueRegiontarget },
  data() {
    return {
      // 当前地域数据
      regionTarget: null,
      // 是否显示地域弹窗
      showRegionTarget: false,
      // 账户列表
      expandList: [],

      // 账户列表
      tempexpandList: [],
      //市场列表
      bazaarList: [],
      // 表格高度
      defaultHeight: 0,
      // 筛选日期范围
      daterange: this.getDaterange(),
      // 日期时间选择器快捷项
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime());
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000);
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 7 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 15 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 30 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 90 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 180 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 365 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 表格数据接口
      url: "/feedBossReport/read",
      // 表格列配置
      columns: [
        {
          columnKey: "index",
          type: "index",
          width: 80,
          label: "序号",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          prop: "username",
          slot: "username",
          label: "推广账户",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "bazaarId",
          label: "推广市场",
          slot: "bazaarId",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          width: 100,
          prop: "userStat",
          label: "账户状态",
          slot: "userStat",
          sortable: true,
        },
        {
          prop: "budget",
          slot: "budget",
          label: "账户预算",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "balance",
          label: "账户余额",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "cost",
          label: "账户消费",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "cash",
          slot: "cash",
          label: "现金消费",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "accessnumber",
          label: "访问次数",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "impression",
          label: "账户展现",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "clicks",
          label: "账户点击",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "cpc",
          label: "CPC",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          prop: "ctr",
          slot: "ctr",
          label: "点击率",
          sortable: true,
          resizable: false,
        },
        {
          width: 100,
          prop: "copynumber",
          label: "目标转化量",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          width: 110,
          prop: "copycost",
          label: "目标转化成本",
          sortable: true,
          resizable: false,
        },
        // {
        //   prop: "copynumberex",
        //   label: "复制数",
        //   sortable: true,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "copycostex",
        //   label: "复制成本",
        //   sortable: true,
        //   resizable: false,
        // },
        // {
        //   prop: "ocpc",
        //   label: "回传数",
        //   sortable: true,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "ocpccost",
        //   slot: "ocpccost",
        //   label: "回传成本",
        //   sortable: true,
        //   showOverflowTooltip: true,
        // },
        {
          prop: "lastDatetime",
          label: "同步时间",
          sortable: true,
          slot: "lastDatetime",
          showOverflowTooltip: true,
        },
        {
          columnKey: "action",
          label: "推广地区",
          resizable: false,
          slot: "action",
        },
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
    };
  },

  created() {
    window.addEventListener("resize", this.setHeight);
    this.setHeight();
  },

  methods: {
    sortChange() {
      return false;
    },

    getOcpccost(cost, ocpc) {
      if (ocpc == 0) {
        return cost;
      }
      if (cost < 1) {
        return cost;
      }
      let ret = cost / ocpc;
      return ret.toFixed(2);
    },

    popoverHide() {
      const popover = document.getElementsByClassName("cash-remove-popover");
      for (let i = 0; i < popover.length; i++) {
        popover[i].remove();
      }
    },

    changebazaarId(id) {
      this.expandList = [];
      this.where.userid = "";
      for (let i = 0; i < this.tempexpandList.length; i++) {
        if (this.tempexpandList[i].bazaarId === id) {
          this.expandList.push(this.tempexpandList[i]);
        }
      }
      this.reload();
    },

    getcolumn(data, column, integer) {
      if (data.length === 0) {
        return 0;
      }
      let sums = 0;
      const values = data.map((item) => Number(item[column]));
      if (!values.every((value) => isNaN(value))) {
        sums = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      }
      if (integer) {
        return sums;
      }
      return sums.toFixed(2);
    },

    summaries(param) {
      const result = [];
      let sum1 = 0,
        sum2 = 0,
        sum3 = 0;
      const { columns, data } = param;
      columns.forEach((column, index) => {
        if (column.property === "budget") {
          result[index] = "合计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (
          [
            "balance",
            "cost",
            "cash",
            "impression",
            "clicks",
            "cpc",
            "ctr",
            "copynumber",
            "copycost",
            "ocpccost",
            "copynumberex",
            "copycostex",
            "ocpc",
          ].indexOf(column.property) > -1
        ) {
          let number = values.reduce((prev, curr) => {
            return this.formatNumber(prev, curr);
          }, 0);

          if (number > 0 && number % 1 !== 0) {
            number = parseFloat(number);
            number = number.toFixed(2);
          }

          if (["ctr"].indexOf(column.property) > -1) {
            result[index] = number + "%";
          } else {
            result[index] = number;
          }

          switch (column.property) {
            case "cost":
              sum1 = this.getcolumn(data, column.property, true);
              break;

            case "ocpc":
              sum2 = this.getcolumn(data, column.property, true);
              break;

            case "ocpccost":
              result[index] = this.getOcpccost(sum1, sum2);
              break;

            case "copynumberex":
              sum3 = this.getcolumn(data, column.property, true);
              break;

            case "copycostex":
              result[index] = this.getOcpccost(sum1, sum3);
              break;
          }
        } else {
          result[index] = "";
        }
      });

      result[11] = (result[6] / result[10]).toFixed(2) == 'NaN' ?  0 : (result[6] / result[10]).toFixed(2)
      result[12] = (result[10] / result[9]).toFixed(2) == 'NaN' ?  0 : (result[10] / result[9]).toFixed(2)
     // result[14] = (result[7] / result[13]).toFixed(2)
      console.log(result)
      return result;
    },

    formatNumber(prev, curr) {
      const value = Number(curr);
      if (!isNaN(value)) {
        return prev + curr;
      }
      return prev;
    },

    asterisk(str, string) {
      const prefixLen = 2,
        suffixLen = 2,
        len = str.length - prefixLen - suffixLen;
      let result = "";
      for (let i = 0; i < len; i++) {
        result += string;
      }
      return (
        str.substring(0, prefixLen) +
        result +
        str.substring(str.length - suffixLen)
      );
    },

    parseData(res) {
      if (res.code === 0) {
        this.bazaarList = res.bazaar;
        this.tempexpandList = res.expand;
      }
      return {
        code: res.code,
        data: res.data,
        count: res.count,
        msg: res.msg,
      };
    },

    openRegion(row) {
      if (!this.$hasPermission("feedbossreport:region")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.$http
        .post("/feedBossReport/getAccountInfo", row)
        .then((res) => {
          if (res.data.code === 0) {
            const findRegion = function (id) {
              for (let i = 0; i < baiduRegion.length; i++) {
                if (baiduRegion[i].id === id) {
                  return baiduRegion[i].label;
                }
                for (const item of baiduRegion[i].children) {
                  if (item.id === id) {
                    return item.label;
                  }
                }
              }
              if (id == 9999999) {
                return "全部区域";
              }
              return "海外";
            };
            let regionTarget = [];
            for (let i = 0; i < res.data.regionTarget.length; i++) {
              regionTarget.push({
                id: res.data.regionTarget[i],
                name: findRegion(res.data.regionTarget[i]),
              });
            }
            this.regionTarget = { user: row, city: regionTarget };
            this.showRegionTarget = true;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    getDaterange() {
      let start = new Date();
      start.setTime(start.getTime());
      start =
        start.getFullYear() +
        "-" +
        (start.getMonth() + 1) +
        "-" +
        start.getDate() +
        " 00:00:00";
      let end = new Date();
      end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
      end =
        end.getFullYear() +
        "-" +
        (end.getMonth() + 1) +
        "-" +
        end.getDate() +
        " 00:00:00";
      return [start, end];
    },

    /* 日期选择改变回调 */
    onDateRangeChoose() {
      if (this.daterange && this.daterange.length === 2) {
        this.where.createTimeStart = this.daterange[0];
        this.where.createTimeEnd = this.daterange[1];
      } else {
        this.where.createTimeStart = null;
        this.where.createTimeEnd = null;
      }
    },

    /*设置表格高度*/
    setHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      let daterange = this.getDaterange();
      if (daterange.length === 2) {
        this.where.createTimeStart = daterange[0];
        this.where.createTimeEnd = daterange[1];
      }
      this.reload();
    },

    /*时间格式化*/
    formatTime(value) {
      const stamp = new Date().getTime() - new Date(value).getTime();
      if (stamp >= 1000 * 60 * 60 * 24) {
        return ((stamp / 1000 / 60 / 60 / 24) | 0) + "天前";
      } else if (stamp >= 1000 * 60 * 60) {
        return ((stamp / 1000 / 60 / 60) | 0) + "小时前";
      } else if (stamp >= 60000) {
        //1分钟以内为：刚刚
        return ((stamp / 1000 / 60) | 0) + "分钟前";
      }
      return "刚刚";
    },
  },
};
</script>

<style scoped>
.ele-body-layout /deep/ .el-table .el-table__footer-wrapper .cell {
  font-weight: bold;
  font-size: 13px;
  padding-left: 10px;
  padding-right: 10px;
}
</style>
